#!/bin/bash 
source ./utils.sh 

ip=$1 
name=${2-Null}
image=${3-Null}
flavor=${4-Null}
floating_ip_part=$(echo ${ip} | awk -F "." '{print $NF}') 


function check_floating(){ 

bash ${project_dir}/floating.sh -l | sed 's/.*ip_address=\(.*\), subnet_id=.*/\1/g' | grep -q ${ip} 
if [[ $? != 0 ]]; then 
    #false Create 
    echo "Create ${ip}" 
    bash ${project_dir}/floating.sh -i ${ip} 
    return $? 
else 
    Infor=$(bash $project_dir/floating.sh -l | grep ${ip} | grep "172.20") 
    if [[ $? != 0 ]]; then 
        #false , descrption health 
	echo "health" 
	return 0 
    else 
        echo "[Error] This IP is already in use: ${ip} 
| ID                                   | Floating IP Address | Fixed IP Address | Port                                 | Floating Network                     | Project  | 
${Infor}" 
	return 1 
    fi 
fi 
} 


function check_local_ip(){

bash ${project_dir}/port.sh -l | sed 's/.*ip_address=\(.*\), subnet_id=.*/\1/g'  | grep "172.20.200.${floating_ip_part}"
if [[ $? != 0 ]]; then
    #Create server
    bash ${project_dir}/boot.sh -c ${name} ${image} "172.20.200.${floating_ip_part}" ${flavor}

else
    port_status=$(bash ${project_dir}/port.sh -l | grep "172.20.200.${floating_ip_part}" | awk '{print $(NF-1)}')
    if [[ ${port_status} == 'ACTIVE' ]] ;then
        echo "This Local_ip 172.20.200.${floating_ip_part}, Being used"
        return 1
    else
        #search local ip ID
        local_Ip_ID=$(bash ${project_dir}/port.sh -l | grep "172.20.200.${floating_ip_part}" | awk '{print $2}')
        #delete local ip
        infor=$(bash ${project_dir}/port.sh -d ${local_Ip_ID})
        if [[ $? != 0 ]];then
            echo ${infor}
            return 1
        fi
        #create boot
        infor=$(bash ${project_dir}/boot.sh -c ${name} ${image} "172.20.200.${floating_ip_part}" ${flavor})
        code_test=$?
        echo "$code_test"
        if  [[ ${code_test} != 0 ]];then
            echo ${infor}
            return 1
        fi
    fi
fi   

}


infor=$(check_floating) 
if [[ $? != 0 ]]; then 
    echo "${infor}" 
    exit 1 
fi 


infor=$(check_local_ip)
if [[ $? != 0 ]]; then
    echo "${infor}"
    exit 1
fi


#time_num=5
#custom_sleep_time="5"
#while (( ${time_num} > 0 ))
#do
#    infor=$(bash -x ${project_dir}/floating.sh -b ${name} ${ip} ${custom_sleep_time} )
#    return_code=$?
#    if [[ ${return_code} != 0 ]]; then
#        sleep 2
#        time_num=$(( time_num - 1 ))
#        continue
#    else
#        break
#    fi
#done


#if [[ ${return_code} != 0 ]];then
#    echo ${infor}
#    exit 1
#fi
